/*
silverPDF is sponsored by Aleyant Systems (http://www.aleyant.com)

silverPDF is based on PdfSharp (http://www.pdfsharp.net) and iTextSharp (http://itextsharp.sourceforge.net)

Developers: Ai_boy (aka Oleksii Okhrymenko)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above information and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR SPONSORS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.IO;

namespace Booklet
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            fileStream = Application.GetResourceStream(
                new Uri("Booklet;component/PDFs/PortableDocumentFormat.pdf", UriKind.RelativeOrAbsolute)).Stream;
        }

        Stream fileStream;

        private void saveButton1_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog d = new SaveFileDialog();
            d.Filter = "PDF file format|*.pdf";

            if (d.ShowDialog() == true)
            {
                // Create the output document
                PdfDocument document = new PdfDocument();

                // Show single pages
                // (Note: one page contains two pages from the source document.
                //  If the number of pages of the source document can not be
                //  divided by 4, the first pages of the output document will
                //  each contain only one page from the source document.)
                document.PageLayout = PdfPageLayout.SinglePage;

                XGraphics gfx;
                XRect box;

                // Open the external document as XPdfForm object
                XPdfForm form = XPdfForm.FromStream(fileStream);
                // Determine width and height
                double ext_width = form.PixelWidth;
                double ext_height = form.PixelHeight;

                int InputPages = form.PageCount;
                int sheets = InputPages / 4;
                if (sheets * 4 < InputPages)
                    sheets += 1;
                int allpages = 4 * sheets;
                int vacats = allpages - InputPages;


                for (int idx = 1; idx <= sheets; idx += 1)
                {
                    // Front page of a sheet:
                    // Add a new page to the output document
                    PdfPage page = document.AddPage();
                    page.Orientation = PageOrientation.Landscape;
                    page.Width = 2 * ext_width;
                    page.Height = ext_height;
                    double width = page.Width;
                    double height = page.Height;

                    gfx = XGraphics.FromPdfPage(page);

                    // Skip if left side has to remain blank
                    if (vacats > 0)
                        vacats -= 1;
                    else
                    {
                        // Set page number (which is one-based) for left side
                        form.PageNumber = allpages + 2 * (1 - idx);
                        box = new XRect(0, 0, width / 2, height);
                        // Draw the page identified by the page number like an image
                        gfx.DrawImage(form, box);
                    }

                    // Set page number (which is one-based) for right side
                    form.PageNumber = 2 * idx - 1;
                    box = new XRect(width / 2, 0, width / 2, height);
                    // Draw the page identified by the page number like an image
                    gfx.DrawImage(form, box);

                    // Back page of a sheet
                    page = document.AddPage();
                    page.Orientation = PageOrientation.Landscape;
                    page.Width = 2 * ext_width;
                    page.Height = ext_height;

                    gfx = XGraphics.FromPdfPage(page);

                    // Set page number (which is one-based) for left side
                    form.PageNumber = 2 * idx;
                    box = new XRect(0, 0, width / 2, height);
                    // Draw the page identified by the page number like an image
                    gfx.DrawImage(form, box);

                    // Skip if right side has to remain blank
                    if (vacats > 0)
                        vacats -= 1;
                    else
                    {
                        // Set page number (which is one-based) for right side
                        form.PageNumber = allpages + 1 - 2 * idx;
                        box = new XRect(width / 2, 0, width / 2, height);
                        // Draw the page identified by the page number like an image
                        gfx.DrawImage(form, box);
                    }
                }

                // Save the document...
                document.Save(d.OpenFile());
            }
        }
    }
}
